package com.flow.demo.module.gd.service.address;

import com.flow.demo.module.gd.dal.mysql.list.ListMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import com.flow.demo.module.gd.controller.admin.address.vo.*;
import com.flow.demo.module.gd.dal.dataobject.address.AddressDO;
import com.flow.demo.framework.common.pojo.PageResult;
import com.flow.demo.framework.common.util.object.BeanUtils;

import com.flow.demo.module.gd.dal.mysql.address.AddressMapper;

import javax.annotation.Resource;

import static com.flow.demo.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.flow.demo.module.gd.enums.ErrorCodeConstants.ADDRESS_NOT_EXISTS;

/**
 * 收获地址 Service 实现类
 *
 * @author Pompey_hpy
 */
@Service
@Validated
public class AddressServiceImpl implements AddressService {

    @Resource
    private AddressMapper addressMapper;

    @Resource
    private ListMapper listMapper;

    @Override
    public Integer createAddress(AddressSaveReqVO createReqVO) {
        // 插入
        AddressDO address = BeanUtils.toBean(createReqVO, AddressDO.class);
        addressMapper.insert(address);
        // 返回
        return address.getId();
    }

    @Override
    public void updateAddress(AddressSaveReqVO updateReqVO) {
        // 校验存在
        validateAddressExists(updateReqVO.getId());
        // 更新
        AddressDO updateObj = BeanUtils.toBean(updateReqVO, AddressDO.class);
        addressMapper.updateById(updateObj);
    }

    @Override
    public void deleteAddress(Integer id) {
        AddressDO addressDO = addressMapper.selectById(id);
        if ( addressDO == null) {
            throw exception(ADDRESS_NOT_EXISTS);
        }

        // 删除地址
        addressMapper.deleteById(id);

        //删除中奖
        listMapper.delete(addressDO.getGdListId());

    }

    private void validateAddressExists(Integer id) {
        if (addressMapper.selectById(id) == null) {
            throw exception(ADDRESS_NOT_EXISTS);
        }
    }

    @Override
    public AddressDO getAddress(Integer id) {
        return addressMapper.selectById(id);
    }

    @Override
    public PageResult<AddressDO> getAddressPage(AddressPageReqVO pageReqVO) {
        return addressMapper.selectPage(pageReqVO);
    }

}